# -*- coding: utf-8 -*-
"""
Created on Sat Dec 24 13:44:49 2022

@author: DELL
"""
import jieba
import json
import eel
import math
import os
class Retrieval:
    input_value = []    #搜索框输入值分词表
    doc_dict = {}   #文档集合
    def __init__(self):
        with open("index_library.json",'r') as load_f:
             self.index_table = json.load(load_f)   #加载索引表
            
        self.doc_num = len(os.listdir('./json'))    #文档总数

    def read_json(self, path):
        with open(path,'r') as load_f:
             load_dict = json.load(load_f)
        return load_dict
    #解析搜索框的输入值
    def parse_value(self, value):
        self.input_value = jieba.lcut_for_search(value)
    #利用索引表搜索相关文档
    def search(self):
        for value in self.input_value:
            #判断词是否在索引表内
            if value in self.index_table.keys():
                #把当前词条对应的所有文档ID加载到文档集合中
                for docId in self.index_table[value].keys():
                    #判断docId是否在文档集合内
                    if docId in self.doc_dict.keys():
                        #在当前docId对应的字典中添加value词条及其出现次数
                        self.doc_dict[docId][value] = self.index_table[value][docId]
                    else:
                        #在文档集合内添加当前docId
                        self.doc_dict[docId] = {value : self.index_table[value][docId]}

    #对搜索结果排序
    def doc_sort(self):
        for key,value in self.doc_dict.items():
            #累加文档上所有词的TF-IDF值
            tf_idf = 0.0
            for word in value.keys():
                tf_idf = tf_idf + (math.log(value[word]) + 1) * math.log(self.doc_num / len(self.index_table[word]))
            self.doc_dict[key]["TF-IDF"] = tf_idf
            
        #按TF-IDF进行一轮排序
        self.doc_dict = sorted(self.doc_dict.items(), key = lambda x: x[1]["TF-IDF"], reverse = True)
        
        #按关键字覆盖率进行二轮排序
        self.doc_dict = sorted(self.doc_dict, key = lambda x: len(x[1]), reverse = True)

        #最多返回100个搜索结果
        return self.doc_dict[:100]
    
    def read_doc(self, doc_list):
        result_list = []
        for doc in doc_list:
            doc = self.read_json('./json/' + doc[0] + '.json')
            result_list.append([doc['title'], doc['store_name'], "https:" + doc['url']]) 
        return result_list    
        
    def run(self, value):
        self.parse_value(value)
        self.search()
        result_list = self.read_doc(self.doc_sort())
        self.doc_dict = {}
        return result_list


@eel.expose
def transfer_to_back(value):
    
    result_list = retrieval.run(value)
    
    eel.transfer_to_front(result_list)  # 调用js文件里的函数，将结果返回去


if __name__ == '__main__':
    retrieval = Retrieval()
    
    web_app_options = {
        'port': 8080
    }
    eel.init("web")
    eel.start("searchEngine.html", options = web_app_options,suppress_error = True)

    